package it.greg.findparty.android.util;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class Localizzatore implements LocationListener{
	
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000; // 1 minute
	
	public Location getPositionLocation(Context c) {
		LocationManager locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
		boolean isNetworkEnabled;
		//boolean isGPSEnabled;
		//isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		Location location = null;
		//Mi basta usare solo la posizione approssimativa
		if (isNetworkEnabled) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            if (locationManager != null) {
                Location tempLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (tempLocation != null)
                    location = tempLocation;
            }
        }
		locationManager.removeUpdates(this);
		return location;
	}
	
	/*
	 * Restituisce la posizione corrente dell'utente in coordinate
	 */
	public String getPositionString(Context c){
		Location location = getPositionLocation(c);
		return location.getLatitude() +","+ location.getLongitude();
	}
	
	/*
	 * Restituisce l'indirizzo corrente presso il quale si trova l'utente
	 */
	public String getPositionAddress(Context c){
		Location location = getPositionLocation(c);
		Geocoder g = new Geocoder(c);
		try {
			List<Address> indirizzi = g.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
			String result = "";
			Address indirizzo = indirizzi.get(0);
			for (int i=0;i < indirizzo.getMaxAddressLineIndex();i++){
				result += " " + indirizzo.getAddressLine(i);
			}
			return result.substring(1);
		} catch (IOException e) {
			return null;
		}
	}
	
	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}

}
